import cv2
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d

from utils.numpyimage2base64png import numpyimage2base64png


def get_threshold_image(npimage, json_content):
    color_enabled = json_content['colorEnabled']
    normal_threshold = json_content['normalThreshold']
    min = json_content['min']
    max = json_content['max']
    if min > max:
        t = min; min = max; max = t
    if not color_enabled:
        gray_img = cv2.cvtColor(npimage, cv2.COLOR_BGR2GRAY)
        gray_img = cv2.normalize(gray_img, None, 0, 255, cv2.NORM_MINMAX)

        binary2 = gray_img
        if normal_threshold:
            binary2 = cv2.threshold(gray_img, min, max, cv2.THRESH_BINARY_INV)[1]

            skeleton = np.zeros_like(binary2)
            skeleton = cv2.bitwise_not(cv2.ximgproc.thinning(binary2, skeleton))

            binary2 = np.minimum(skeleton, binary2)

            # 定义一组点的坐标
            points = np.array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]])

            # 创建Voronoi图
            vor = Voronoi(points)
            t = 1999
        else:
            binary2 = cv2.adaptiveThreshold(
                #npimage[:, :, 0],
                gray_img,
                maxValue=max,
                adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                thresholdType=cv2.THRESH_BINARY, blockSize=11, C=min)
        imagesrc = numpyimage2base64png(binary2)
        return imagesrc
    else:
        imagesrc = numpyimage2base64png(npimage)
        return imagesrc